import { FC, useEffect, useState } from "react";
import ScreenAdapter from "@/components/ScreenAdapter";
import { Button, Form, Input, message } from "antd";
import { UserForm } from "@/api/user/models";
import { userApi } from "@/api";
import { encryptPwd } from "@/utils/crypto";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { setTokenAction } from "@/store/user/action";
import storage from "@/utils/storage";

const Login: FC = () => {
  const [messageApi, contextHolder] = message.useMessage()
  const [loginForm, setLoginForm] = useState<UserForm>({
    captcha: '', // 图片
    code: '', // 短信
    password: '',
    username: '',
    uuid: ''
  })
  const [captchaImageUrl, setCaptchaImageUrl] = useState<string>('')
  const navigate = useNavigate()
  const dispatch = useDispatch()

  const handleLogin = async () => {
    // 登录逻辑操作
    if (!loginForm.captcha || !loginForm.password || !loginForm.username) return

    const data = { ...loginForm, password: encryptPwd(loginForm.password, 'tls#&*aeskey2022') }

    try {
      const res = await userApi.userLogin(data)
      if (res.code !== 200) {
        return messageApi.open({
          type: 'error',
          content: res.msg
        })
      }

      // 存储token
      storage.sessionStorage.set('token', res.data.token)
      dispatch(setTokenAction(res.data.token))

      // 跳转: 数据资产目录
      navigate('/dataAsset', {})
    } catch (error) {
      console.error('登录错误', error)
    }
  }

  const changeLoginForm = function<K extends keyof UserForm, V extends UserForm[K]>(key: K, value: V) {
    setLoginForm((origin) => ({
      ...origin,
      [key]: value
    }))
  }

  // 获取图片验证码
  const handleCaptchaImage = async () => {
    try {
      const res = await userApi.getCaptchaImage()

      if (res.code === 200) {
        setCaptchaImageUrl('data:image/gif;base64,' + res.data.img)
        changeLoginForm('uuid', res.data.uuid)
        changeLoginForm('code', '888888')
      }
    } catch (error) {
      console.log('获取图片验证码失败：', error)
    }
  }

  useEffect(() => {
    handleCaptchaImage()
  }, [])

  return (
    <div className="w-full h-full bg-dark-100">
      {contextHolder}
      <div className="absolute-center w-358px p-20px bg-[#fff] shadow-md rounded-8px">
        <div className="h-24px leading-24px text-center">数字化转型服务大平台</div>
        <Form
          style={{ maxWidth: 600 }}
        >
          <Form.Item name="username" label="用户名" rules={[{ required: true }]}>
            <Input placeholder="请输入用户名" 
              value={loginForm.username} 
              onInput={(e) => changeLoginForm('username', (e.target as HTMLInputElement).value)}
            ></Input>
          </Form.Item>
          <Form.Item name="password" label="密码" rules={[{ required: true }]}>
            <Input
              placeholder="请输入密码"
              value={loginForm.password}
              onInput={(e) => changeLoginForm('password', (e.target as HTMLInputElement).value)}
            ></Input>
          </Form.Item>
          <Form.Item name="capture" label="图片验证码" rules={[{ required: true }]}>
            <div className='flex items-center'>
              <Input 
                placeholder="请输入图片验证码"
                value={loginForm.captcha}
                onInput={(e) => changeLoginForm('captcha', (e.target as HTMLInputElement).value)}
              ></Input>

              <img className="w-100px h-40px" src={captchaImageUrl} alt="" />
            </div>
          </Form.Item>

          <Form.Item>
            <Button type="primary" onClick={handleLogin}>登录</Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default Login